package com.rajaev.dtu.tractor.domain.repository.mongo;

import com.alibaba.fastjson.JSONObject;
import com.rajaev.dtu.tractor.domain.entity.BatteryPo;
import com.rajaev.dtu.tractor.domain.entity.SnotiMessage;
import com.rajaev.dtu.tractor.infrastructure.helper.MongoDbUtils;
import org.bson.BsonDocument;
import org.bson.Document;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Component
public class SnotiMessageRepository {
    @Resource
    public MongoDbUtils mongoDbUtils;

    private final static String collection_name = "snotiMessage";

    public void saveInMongo(JSONObject jsonObject){
        Document document =   Document.parse(jsonObject.toJSONString());
        mongoDbUtils.getDatabase().getCollection(collection_name).insertOne(document);
    }


    public JSONObject createCommonMongoMessageHeader(BatteryPo batteryPo, SnotiMessage snotiMessageDto) {
       JSONObject jsonObject = new JSONObject();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalDateTime nowDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(new BigDecimal(snotiMessageDto.getCreated_at()).intValue()), ZoneId.of("Asia/Shanghai"));
        jsonObject.put("did", snotiMessageDto.getDid());
        jsonObject.put("mac", snotiMessageDto.getMac());
        jsonObject.put("created_at", new BigDecimal(snotiMessageDto.getCreated_at()).intValue());
        jsonObject.put("log_date", dateFormatter.format(nowDateTime));
        jsonObject.put("log_time", timeFormatter.format(nowDateTime));
        jsonObject.put("type", snotiMessageDto.getEvent_type());
        jsonObject.put("save_time", new Date().getTime() / 1000);
        String vin = batteryPo.getVin();
        if (vin == null) {
            vin = "0000000000000000000000000";
        }
        jsonObject.put("vin", vin);
        jsonObject.put("msgId", snotiMessageDto.getMsg_id());
        jsonObject.put("data",snotiMessageDto.getData());
        return jsonObject;
    }

}



